#include "course.h"
#include "../Include/log_pub.h"
#include "../Include/data_input.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

// 初始化课程链表
void init_course_list(CourseList *head) {
    *head = (CourseNode*)malloc(sizeof(CourseNode));
    if (!*head) { perror("内存分配失败"); exit(1); }
    (*head)->next = NULL;
}

// 按编号查找课程
CourseNode* find_course_inner(CourseList head, const char *course_id) {
    CourseNode *p = head->next;
    while (p) {
        if (strcmp(p->id, course_id) == 0) return p;
        p = p->next;
    }
    return NULL;
}

// 新增课程
void add_course(CourseList head) {
    CourseNode *new_course = (CourseNode*)malloc(sizeof(CourseNode));
    printf("请输入课程编号：");
    scanf("%s", new_course->id);
    clear_input_buffer();
    
    // 检查课程编号是否重复
    if (find_course_inner(head, new_course->id)) {
        printf("课程编号已存在！新增失败\n");
        free(new_course);
        return;
    }
    
    printf("请输入课程名称：");
    scanf("%s", new_course->name);
    printf("请输入课程性质（必修/选修）：");
    scanf("%s", new_course->type);
    printf("请输入学时：");
    scanf("%d", &new_course->hours);
    printf("请输入学分：");
    scanf("%d", &new_course->credit);
    printf("请输入人数上限：");
    scanf("%d", &new_course->max);
    clear_input_buffer();
    new_course->selected = 0;
    new_course->next = NULL;

    // 插入链表尾部
    CourseNode *p = head;
    while (p->next) p = p->next;
    p->next = new_course;

    printf("新增课程成功！\n");
    char log[256];
    sprintf(log, "新增课程：%s %s", new_course->id, new_course->name);
    write_log(log);
    save_data(NULL, head);  // 保存课程数据
}

// 删除课程
void del_course(CourseList *c_head, StudentList s_head) {
    char course_id[20];
    printf("请输入要删除的课程编号：");
    scanf("%s", course_id);
    clear_input_buffer();

    CourseNode *c_p = (*c_head)->next, *c_prev = *c_head;
    while (c_p) {
        if (strcmp(c_p->id, course_id) == 0) {
            int course_credit = c_p->credit;

            // 同步所有学生的选课记录和学分
            StudentNode *s_p = s_head->next;
            while (s_p) {
                // 查找并移除课程ID
                char *pos = strstr(s_p->course_ids, course_id);
                if (pos) {
                    int len = strlen(course_id);
                    int is_valid = 0;
                    if (pos == s_p->course_ids) {
                        if (pos[len] == '\0' || pos[len] == ',') is_valid = 1;
                    } else if (pos[-1] == ',') {
                        if (pos[len] == '\0' || pos[len] == ',') is_valid = 1;
                    }

                    if (is_valid) {
                        int del_len = len;
                        if (pos[len] == ',') del_len++;
                        memmove(pos, pos + del_len, strlen(pos + del_len) + 1);
                        // 扣减学分
                        s_p->total_credit -= course_credit;
                        if (s_p->total_credit < 0) s_p->total_credit = 0;
                    }
                }
                s_p = s_p->next;
            }

            // 从课程链表中删除
            c_prev->next = c_p->next;
            free(c_p);
            printf("删除课程成功！\n");
            char log[100];
            sprintf(log, "删除课程：%s", course_id);
            write_log(log);
            save_data(s_head, *c_head);
            return;
        }
        c_prev = c_p;
        c_p = c_p->next;
    }
    printf("课程不存在！删除失败\n");
}

// 修改课程信息
void modify_course(CourseList head) {
    char course_id[20];
    printf("请输入要修改的课程编号：");
    scanf("%s", course_id);
    clear_input_buffer();

    CourseNode *course = find_course_inner(head, course_id);
    if (!course) {
        printf("课程不存在！修改失败\n");
        return;
    }

    printf("当前课程名称：%s，请输入新名称：", course->name);
    scanf("%s", course->name);
    printf("当前课程性质：%s，请输入新性质（必修/选修）：", course->type);
    scanf("%s", course->type);
    printf("当前学时：%d，请输入新学时：", course->hours);
    scanf("%d", &course->hours);
    printf("当前学分：%d，请输入新学分：", course->credit);
    scanf("%d", &course->credit);
    printf("当前人数上限：%d，请输入新上限：", course->max);
    scanf("%d", &course->max);
    clear_input_buffer();

    printf("修改课程信息成功！\n");
    char log[256];
    sprintf(log, "修改课程信息：%s", course_id);
    write_log(log);
    save_data(NULL, head);  // 保存课程数据
}

// 查看课程详情
void query_course_detail(CourseList c_head, StudentList s_head) {
    char course_id[20];
    printf("请输入要查询的课程编号：");
    scanf("%s", course_id);
    clear_input_buffer();

    CourseNode *course = find_course_inner(c_head, course_id);
    if (!course) {
        printf("课程不存在！\n");
        return;
    }

    printf("\n课程详情\n");
    printf("编号：%s | 名称：%s | 性质：%s\n", course->id, course->name, course->type);
    printf("学时：%d | 学分：%d | 已选人数：%d/%d\n",
           course->hours, course->credit, course->selected, course->max);
    printf("已选学生：");
    
    // 查找选了该课程的学生
    StudentNode *s_p = s_head->next;
    int has_student = 0;
    while (s_p) {
        char temp_ids[200];
        strcpy(temp_ids, s_p->course_ids);
        char *token = strtok(temp_ids, ",");
        while (token) {
            if (strcmp(token, course_id) == 0) {
                printf("%s（学号：%s） ", s_p->name, s_p->id);
                has_student = 1;
                break;
            }
            token = strtok(NULL, ",");
        }
        s_p = s_p->next;
    }
    if (!has_student) printf("无");
    printf("\n");
    char log[100];
    sprintf(log, "查询课程：%s", course_id);
    write_log(log);
}

// 查看所有课程
void show_all_courses(CourseList head) {
    CourseNode *p = head->next;
    if (!p) {
        printf("暂无课程信息！\n");
        return;
    }

    printf("\n所有课程列表\n");
    while (p) {
        printf("编号：%s | 名称：%s | 学分：%d | 已选：%d/%d\n",
               p->id, p->name, p->credit, p->selected, p->max);
        p = p->next;
    }
    write_log("查看所有课程列表");
}
